package com.shj.service.impl;

import com.shj.dao.SysRoleMapper;
import com.shj.entity.SysRole;
import com.shj.entity.SysRoleMenu;
import com.shj.service.SysRoleMenuService;
import com.shj.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description TODO
 * @Author songhuajian
 * @Date 2020/4/28 14:10
 **/
@Service("sysRoleService")
public class SysRoleSeriveImpl implements SysRoleService {
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Override
    public List<SysRole> findAll() {
        return sysRoleMapper.findAll();
    }

    @Override
    public SysRole findByRoleId(String roleId) {
        return sysRoleMapper.selectByRoleId(roleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int add(SysRole sysRole, String[] menus) {
        // 添加角色权限
        SysRoleMenu sysRoleMenu = new SysRoleMenu();
        sysRoleMenu.setRoleId(sysRole.getRoleId());
        for (String menuId : menus) {
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenuService.add(sysRoleMenu);
        }
        // 添加角色信息
        return sysRoleMapper.insert(sysRole);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(SysRole sysRole, String[] menus) {
        // 删除原来的角色权限
        sysRoleMenuService.delete(sysRole.getRoleId());
        // 添加新的角色权限
        SysRoleMenu sysRoleMenu = new SysRoleMenu();
        sysRoleMenu.setRoleId(sysRole.getRoleId());
        for (String menuId : menus) {
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenuService.add(sysRoleMenu);
        }
        // 更新角色信息
        return sysRoleMapper.update(sysRole);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(String roleId) {
        // 删除角色权限
        sysRoleMenuService.delete(roleId);
        // 删除角色信息
        return sysRoleMapper.delete(roleId);
    }
}
